#include "GLheader.h"
#include "ShaderGLSL.h"
#include "Exception.h"
#include "File.h"
#include <vector>
namespace NBE
{
	ShaderGLSL::ShaderGLSL( wchar_t* name)
	{
		
		char* source = NULL;
		std::wstring shaderFileName = std::wstring(name).append(L".vs");
 
		FileIO::readFileIntoStr(shaderFileName,source);
		verSh = glCreateShader(GL_VERTEX_SHADER);
		const char * constStr = (const char *)source;
		glShaderSource(verSh,1,&constStr,NULL);
		delete source;
 
		glCompileShader(verSh);
 
		int success;
		glGetShaderiv(verSh, GL_COMPILE_STATUS, &success);
		int length;
		glGetShaderiv (verSh, GL_INFO_LOG_LENGTH, &length);
		char log[1024];
		glGetShaderInfoLog (verSh, length, &length, log);
		if (success == GL_FALSE)
		{
			throw NBEException(VertexShaderError);
		}
 
		shaderFileName = std::wstring(name).append(L".ps");
		FileIO::readFileIntoStr(shaderFileName,source);
 
		fragSh = glCreateShader(GL_FRAGMENT_SHADER);
		constStr = (const char *)source;
		glShaderSource(fragSh,1, &constStr,NULL);
		delete source;
 
		glCompileShader(fragSh);
 
		glGetShaderiv(fragSh, GL_COMPILE_STATUS, &success);
 
		glGetShaderiv (fragSh, GL_INFO_LOG_LENGTH, &length);
 
		glGetShaderInfoLog (fragSh, length, &length, log);
		if (success == GL_FALSE)
		{
			throw NBEException(PixelShaderError);
		}
		m_program = glCreateProgram();
 
		glAttachShader(m_program,verSh);
		glAttachShader(m_program,fragSh);
 
		//mapping the attribute name and the location
		//TODO: auto read from the vertex shader ?


		{
			glBindAttribLocation(m_program, POS, "apos");
			glBindAttribLocation(m_program, TEXCOORD0, "atexcoord0");
		 	glBindAttribLocation(m_program,COLOR,"acolor");
			glBindAttribLocation(m_program, NORMAL, "anormal");
		}
 
		glLinkProgram(m_program);
		glGetShaderiv(m_program, GL_LINK_STATUS, &success);
		glGetProgramInfoLog (m_program, length, &length, log);
		if (success == GL_FALSE)
		{
			throw NBEException(LinkShaderError);
		}

		 
		
 

		 
	}

	ShaderGLSL::~ShaderGLSL()
	{}
}